//
//  WIFISettingViewController.swift
//  AlterationSwitch
//
//  Created by solarke_apple_mini_1 on 2018/10/25.
//  Copyright © 2018年 石家庄科林电气股份有限公司. All rights reserved.
//

import UIKit
import NetworkExtension
import SystemConfiguration.CaptiveNetwork

class WIFISettingViewController: BaseViewController {
    //socket客户端类对象
    var socketClient:TCPClient?
    
    @IBOutlet var WiFiNameTextField:UITextField!
    @IBOutlet var WiFiPassTextField:UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        WiFiNameTextField.text = UserDefaultsOrNothingValue(WiFiName, defaultValue: "")
        WiFiPassTextField.text = UserDefaultsOrNothingValue(WiFiPassword, defaultValue: "")
    }
    
    @IBAction func touchDown() {
        view.endEditing(true)
    }
    
    @IBAction func textFieldDidEndOnExit(field: UITextField) {
        if field == WiFiNameTextField {
            field.resignFirstResponder()
            WiFiPassTextField.becomeFirstResponder()
        } else {
            field.resignFirstResponder()
        }
    }
    
    @IBAction func setting() {
        if verify() {
            let name = WiFiNameTextField.text!
            if name == getUsedSSID() {
                //showToast("成功连接Wi-Fi")
                SetUserDefaultsString(name, key: WiFiName)
                processClientSocket()
            } else {
                let password = WiFiPassTextField.text!
                wifiRegiser(name: name, password: password)
            }
        }
    }
    
    func verify() -> Bool {
        // 用户名
        let name = WiFiNameTextField.text!
        if stringIsEmpty(name) {
            showToast("请输入无线账号")
            return false
        }
        
        // 密码
        let password = WiFiPassTextField.text!
        if stringIsEmpty(password) {
            showToast("请输入无线密码")
            return false
        }
        
        return true
    }

    func wifiRegiser(name:String,password:String) {
        if #available(iOS 11, *) {
            let hotspotConfig = NEHotspotConfiguration.init(ssid: name, passphrase: password, isWEP: false)
            NEHotspotConfigurationManager.shared.apply(hotspotConfig) { (error) in
                print("error-->\(String(describing: error))")
                if error?.localizedDescription == "already associated." || error == nil {
                    if getUsedSSID() == name {
                        SetUserDefaultsString(name, key: WiFiName)
                        SetUserDefaultsString(password, key: WiFiPassword)
                        processClientSocket()
                    }
                }
            }
        } else {
            showToast("不支持自动连接Wi-Fi")
        }
    }
}
